package com.chilly.other.thread;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * CyclicBarrier 回环栅栏：等待至barrier状态再全部同时执行
 * 可以让一组线程等待至某个状态之后再全部同时执行，叫做回环
 * <p>
 * Created by Chilly Cui on 2020/12/5.
 */
public class CyclicBarrierDemo {

    public static void main(String[] args) {
        int N = 4;
        CyclicBarrier barrier = new CyclicBarrier(N);
        for (int i = 0; i < N; i++) {
            new Writer(barrier).start();
        }
    }

    static class Writer extends Thread {
        private CyclicBarrier cyclicBarrier;

        public Writer(CyclicBarrier barrier) {
            this.cyclicBarrier = barrier;
        }

        @Override
        public void run() {
            try {
                Thread.sleep(5000); //线程睡眠模拟需要写入数据的操作
                System.out.println("线程写入数据完毕，等待其他线程： "+Thread.currentThread().getName());
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
            System.out.println("所有线程写入数据完毕，继续其他操作： "+Thread.currentThread().getName());
        }
    }
}
